/*	
====================================================================================
2008 | John Dalziel  | The Computus Engine  |  http://www.computus.org

All source code licenced under The MIT Licence
====================================================================================  

Accurate Timekeeper in AS3 Example
*/

package 
{
	import com.puppy.timer.PuppyTimer;
	import com.puppy.timer.PuppyTimerEvent;
	
	import flash.display.MovieClip;
	import flash.display.Stage;
	import flash.events.*;
	import flash.text.TextField;
	import flash.utils.getTimer;
	
	public class PuppyMain extends MovieClip
	{
		
		// --------------------------------------------------------------
		// PROPERTIES		
		
		public var puppyTimer:PuppyTimer;
		private var lastTick:Number
		private var cumulativeDrift:Number
		
		// --------------------------------------------------------------
		// CONSTRUCTOR & DESTRUCTOR
		
		private var fps_txt:TextField = new TextField();
		private var d1_txt:TextField = new TextField();
		private var d2_txt:TextField = new TextField();
		private var d3_txt:TextField = new TextField();
		private var xx_txt:TextField = new TextField();
		public function PuppyMain():void
		{
			addChild(fps_txt);
			addChild(d1_txt);
			addChild(d2_txt);
			addChild(d3_txt);
			addChild(xx_txt);
			fps_txt.y = 0;
			d1_txt.y = 50;
			d2_txt.y = 100;
			d3_txt.y = 150;
			xx_txt.y = 200;
			super()
			init()
		}
		
		protected function init():void
		{
			cumulativeDrift = 0
			lastTick = getTimer()
			
			// start timekeeper
			puppyTimer = new PuppyTimer();
			puppyTimer.setRealTimeValue();
			puppyTimer.setRealTimeTick();
			puppyTimer.startTicking();
			puppyTimer.addEventListener(PuppyTimerEvent.CHANGE, onTick);
		}
		// --------------------------------------------------------------
		// EVENTS
		
		private var tttt:int  = 0;
		protected function onTick(event:PuppyTimerEvent):void
		{
			xx_txt.text = "tttt=" + (tttt++);
			// FPS
			fps_txt.text = "fps=" + puppyTimer.getTickDuration() + "ms per " + puppyTimer.getTickFrequency() + "ms"
			
			// TICK
			var newTick = getTimer()
			var expectedTickDuration = 1000 * (puppyTimer.getTickDuration() / puppyTimer.getTickFrequency())
			var actualTickDuration = newTick - lastTick
			lastTick = newTick
			
			// DRIFT
			var tickDrift = actualTickDuration - expectedTickDuration
			cumulativeDrift += tickDrift
			var cumulativeDriftSeconds = cumulativeDrift / 1000
			var sign
			if ( cumulativeDriftSeconds > 0 ) { sign = "+" } else { sign = "-" }
			
			d1_txt.text = "d1=" +expectedTickDuration.toString() + " milliseconds"
			d2_txt.text = "d2=" +actualTickDuration.toString() + " milliseconds"
			d3_txt.text = "d3=" +sign + " " + cumulativeDriftSeconds.toString() + " seconds"
		}
		
	}
}